
// 渲染页面
shoppingCart();
async function shoppingCart() {
  const result = await searchShoppingCar();
  var tbody = document.querySelector("tbody");
  var { status, msg, list, id, goodsid, title, img } = result;
  var shoppingList = list;
  shoppingList.forEach((item) => {
    item.checked = false;
  });
  console.log(shoppingList, "shoppingList");
  if (status) {
    if (list.length) {
      var html = "";
      list.forEach(({ user, gid, buyNum, img, title, priceNum }) => {
        html += `<tr>
              <td class="checkbox"><input class="check-one check" data-gid="${gid}" type="checkbox" /></td>
              <td class="goods"><img src="${img}" alt="" /><span>${title}</span></td>
              <td class="price">${priceNum}</td>
              <td class="count">
                  <span class="reduce">-</span>
                  <input class="count-input" type="text" value="${buyNum}" />
                  <span class="add">+</span>
              </td>
              <td class="subtotal">${priceNum * buyNum}</td>
              <td class="operation"><span class="delete">删除</span></td>
          </tr>`;
      });
      tbody.innerHTML = html;
      //   console.log(listPage)
    } else {
      tbody.textContent = "暂无数据";
    }
  } else {
    alert(msg);
  }
  //   // 点击结算按钮
  //   $("closing").click(function () {
  //     console.log(678);
  //   });

  // 全选
  $(".check-all").click(function () {
    // var status = this.checked;
    var status = $(this).prop("checked");
    console.log(status);
    $(".check-one").prop("checked", status);
    shoppingList.forEach((item) => {
      item.checked = status;
    });
    console.log(shoppingList, "shoppingList-all");

    getTotal();
  });

  // 反选
  // input输入框的事件： onchange   oninput
  $(".check-one").click(function (e) {
    e = e || window.event;
    var gid = e.target.getAttribute("data-gid");
    shoppingList.forEach((item) => {
      if (item.gid == gid) {
        item.checked = e.target.checked;
      }
    });
    // console.log(shoppingList, 'shoppingList');

    isAllChecked();
    getTotal();
  });

  $(".add").click(function () {
    console.log(1111);
    var num = $(this).prev().val();
    num++;
    console.log(num, "num");

    $(this).prev().val(num);

    var price = $(this).parent().prev().text();
    var subtotal = (price * num).toFixed(2);
    $(this).parent().next().text(subtotal);
    $(this).prevAll(".reduce").text("-");

    getTotal();
  });

  $(".reduce").click(function () {
    var num = $(this).next().val();
    if (num <= 1) return false;
    num--;
    if (num == 1) $(this).text("");
    $(this).next().val(num);

    var price = $(this).parent().prev().text();
    var subtotal = (price * num).toFixed(2);
    $(this).parent().next().text(subtotal);
    getTotal();
  });

  $(".delete").click(function () {
    if (confirm("是否删除当前商品?")) {
      $(this).parents("tr").remove();
      isAllChecked();
      getTotal();
    }
  });

  $("#deleteAll").click(function () {
    if (confirm("是否删除选中商品?")) {
      $(".check-one:checked").parents("tr").remove();
      isAllChecked();
      getTotal();
    }
  });
  $("#clearAll").click(function () {
    if (confirm("是否清空购物车?")) {
      $(".check-one").parents("tr").remove();
      isAllChecked();
      getTotal();
    }
  });

  function isAllChecked() {
    var flag = $(".check-one").is(":not(:checked)"); // 是否存在未被选中的 (true:存在 false:不存在)

    $(".check-all").prop(
      "checked",
      $(".check-one").length == 0 ? false : !flag
    );
  }

  function getTotal() {
    var sum = 0;
    var allPrice = 0;
    $(".check-one:checked")
      .parents("tr")
      .each(function () {
        var num = $(this).find(".count-input").val() * 1;
        var subtotal = $(this).find(".subtotal").text() * 1;
        console.log(num, subtotal);
        sum += num;
        allPrice += subtotal;
      });

    $("#selectedTotal").text(sum);
    $("#priceTotal").text(allPrice.toFixed(2));
  }
  $(document).on("click", ".closing", async () => {
    // 总价格
    var total = priceTotal.innerHTML;
    console.log(total, "total");
    // 订单数据
    var orderData = shoppingList.filter((item) => {
      if (item.checked == true) {
        return item;
      }
    });
    console.log(orderData, "orderData");
    if (orderData.length == 0) {
      alert("请选择需要付款的商品");
      return;
    }
    // 请求接口
    var user = getCookie("lgc");
    var orderId = user + new Date().getTime();
    //   把获取到的存到数据库
    var result = await addToSubmit({
      user,
      orderId,
      orderList: JSON.stringify(orderData)
    });
    var { status, msg } = result;
    console.log(result);
    if (status) {
      location.href = `../html/submitOrders.html?orderId=${orderId}`;
    } else {
      alert(msg);
    }
  });
}
